//
//  Shopping_Cart_ViewController.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/4/21.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "Shopping_Cart_ViewController.h"
#import "Shopping_cat_ PaymentTableViewCell.h"
#import "SuccessdMerchant_TableViewCell.h"
#import "Shopping_cat_ListTableViewCell.h"
#import "Shopping_cat_TableViewCell.h"
#import "MyShoppingList_ViewController.h"
#import "ShoppingHotImage_TableViewCell.h"
#import "FinishStockViewController.h"
#import "AddressViewController.h"
#import "ApplyForViewController.h"
#import "InterFace.h"
#import "AllPraceViw.h"
#import "UIViewAdditions.h"
#import "CarView.h"
#import "InformationButton.h"
#import "InfoViewController.h"
#import "ProductListModel.h"
#import "CarModel.h"
#import "AFNetworking.h"
#include "EncryptionData.h"
#import "GMDCircleLoader.h"
#import "Alart_ZhiFuView.h"

#import "AlertView.h"
#import "AccountViewController.h"

#import "Reachability.h"
#import "NetStatus.h"
@interface Shopping_Cart_ViewController ()<UITableViewDataSource,UITableViewDelegate,Shopping_cat__PaymentTableViewCellDelegate,CarModelDelegate,Shopping_cat_TableViewCellDelegate>

{
    
    UIView  *_alertBackview1;
    AlertView *_alerView;
    
    CarView *_allPraceView;
    Alart_ZhiFuView *_zhiFuAlartView;//提交订单时的弹出框
    UIView *_alertBackview;
    UITapGestureRecognizer *_singleTap;
     UITapGestureRecognizer *_singleTap2;
}
@property (nonatomic, copy) NSString *boolbalance; //选择余额
@property (nonatomic,strong)NSMutableArray *carArray;
@property (nonatomic,strong)CarModel *carlistModel;
@property (nonatomic,strong)UILabel *backView;
@end

@implementation Shopping_Cart_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.view.backgroundColor = BackColor;
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    title.text = @"购物车";
    title.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = title;
    
    InformationButton *infonmationBut = [[InformationButton alloc] initWithFrame:CGRectMake(0, 0, 23, 29)];
    infonmationBut.informationNum.text = @"20";
    [infonmationBut setImage:[UIImage imageNamed:@"查看库存_03"] forState:UIControlStateNormal];
    [infonmationBut addTarget:self action:@selector(informationClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBut = [[UIBarButtonItem alloc] initWithCustomView:infonmationBut];
    self.navigationItem.rightBarButtonItem = rightBut;
    
    self.carArray = [NSMutableArray array];
    
    
  
    
    [self createTableView];
    
    


}



#pragma -mark 创建提示框
- (void)createAlertView{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _alertBackview1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview1.backgroundColor = [UIColor blackColor];
    _alertBackview1.alpha = 0.4;
    [window addSubview:_alertBackview1];
    _alerView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_mall_xibs" owner:self options:nil] objectAtIndex:10];
    _alerView.frame = CGRectMake(50, SCREEN_HEIGHT/2.0-130/2.0, SCREEN_WIDTH-100, 130);
    [_alerView.confirmBut addTarget:self action:@selector(confirmButClick1) forControlEvents:UIControlEventTouchUpInside];
    [_alerView.cancelBut addTarget:self action:@selector(cancelButClick1) forControlEvents:UIControlEventTouchUpInside];
    
    _alerView.title.text = @"您还没有缴纳保证金";
    _alerView.describeLabel1.text = @"请尽快缴纳";
    _alerView.describeLabel2.text = @"缴纳保证金方可订购商品";
    [_alerView.confirmBut setTitle:@"去缴纳" forState:UIControlStateNormal];
    [window addSubview:_alerView];
}

#pragma -mark 点击确定
- (void)confirmButClick1{
    [_alertBackview1 removeFromSuperview];
    [_alerView removeFromSuperview];
    
    AccountViewController *offline = [[AccountViewController alloc]init];//绑定状态
    offline.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:offline animated:YES];
}

#pragma -mark 点击提示框稍后按钮
- (void)cancelButClick1{
    [_alertBackview1 removeFromSuperview];
    [_alerView removeFromSuperview];
    
    self.tabBarController.selectedIndex = 0;
    
}
#pragma -mark 点击弹出框的点击手势
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{

    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    [_zhiFuAlartView.password resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        self.navigationController.navigationBarHidden=NO;
    
    
//    NSString *isPayOffDeposit = [[NSUserDefaults standardUserDefaults] objectForKey:@"IsPayOffDeposit"];
//    if ([isPayOffDeposit isEqualToString:@"0"]) {
//        [self createAlertView];
//        return;
//    }

    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    [self.carArray removeAllObjects];
      self.boolbalance = @"0";
    //开始获取购物车页面信息
    self.carlistModel = [[CarModel alloc] init];
    _carlistModel.carModelDelegate = self;
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *dic = @{@"AgentID":agentId};
    [_carlistModel getCarList:self.carArray parameter:dic];
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
}

#pragma -mark创建TableView
- (void)createTableView{
    
    self.myCarTableView = [[UITableView alloc] init];
    double version = [[UIDevice currentDevice].systemVersion doubleValue];//判定系统版本。
    if(version>=9.0f){
        self.myCarTableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    } else{
        self.myCarTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    self.myCarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myCarTableView.delegate = self;
    self.myCarTableView.dataSource = self;

    [self.view addSubview:self.myCarTableView];
    
    self.backView = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.backView.textAlignment = NSTextAlignmentCenter;
    self.backView.backgroundColor = LineColor;
    self.backView .textColor = [UIColor grayColor];
    self.backView .text = @"~购物车空空的,什么也没有";
    self.backView.textColor = [UIColor grayColor];
    self.backView.hidden = YES;
    [self.view addSubview:self.backView];
}

#pragma -mark 创建tableViewFoodVIew
- (UIView *)crezteTableViewFoodView{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 160)];
    
    view.backgroundColor = LineColor;
    
    UIView *backView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , 41)];
    backView.backgroundColor = [UIColor whiteColor];
    [view addSubview:backView];
    UIView *linewiew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    linewiew.backgroundColor = BackColor;
    [view addSubview:linewiew];
    
    UILabel *yu_price = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 60, 30)];
    yu_price.text = @"使用余额(不足部分从银行卡中扣除)";
    yu_price.font = [UIFont fontWithName:nil size:12];
    [view addSubview:yu_price];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-40, yu_price.frame.origin.y, 20, 20)];
    [button setBackgroundImage:[UIImage imageNamed:@"购物车_07"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"购物车２_07"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(selectBut:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    _allPraceView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndex:9];

    _allPraceView.zeKou.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.DiscountPriceAmount.floatValue];
    _allPraceView.yu_e_Price.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.AmountCanUse.floatValue];
    _allPraceView.zonPrice.text= [NSString stringWithFormat:@"总金额:¥%.1f",self.carlistModel.MarketPriceAmount.floatValue];
    _allPraceView.frame = CGRectMake(0, yu_price.bottom, SCREEN_WIDTH, 50);
    [view addSubview:_allPraceView];
    

    //买库存
    UIButton *buyBut = [[UIButton alloc] initWithFrame:CGRectMake(10, _allPraceView.bottom+20, (SCREEN_WIDTH-30)/2.0, 40)];
    [buyBut addTarget:self action:@selector(buyButClick:) forControlEvents:UIControlEventTouchUpInside];
    [buyBut setBackgroundImage:[UIImage imageNamed:@"gouwuche-01"] forState:UIControlStateNormal];
    [view addSubview:buyBut];
    
    NSString *levelID = [[NSUserDefaults standardUserDefaults] objectForKey:@"LevelID"];
    UIButton *butUserBut;
    if (levelID.intValue == 5) {
        buyBut.hidden = YES;
        butUserBut = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-145)/2, _allPraceView.bottom+20, (SCREEN_WIDTH-30)/2.0, 40)];
        [butUserBut addTarget:self action:@selector(butUserButClick:) forControlEvents:UIControlEventTouchUpInside];
        [butUserBut setBackgroundImage:[UIImage imageNamed:@"gouwuche-02"] forState:UIControlStateNormal];
        [view addSubview:butUserBut];
    }
    else{
        buyBut.hidden = NO;
        butUserBut = [[UIButton alloc] initWithFrame:CGRectMake(buyBut.right+10, _allPraceView.bottom+20, (SCREEN_WIDTH-30)/2.0, 40)];
        [butUserBut addTarget:self action:@selector(butUserButClick:) forControlEvents:UIControlEventTouchUpInside];
        [butUserBut setBackgroundImage:[UIImage imageNamed:@"gouwuche-02"] forState:UIControlStateNormal];
        [view addSubview:butUserBut];
    }
    //买给客户

    
    return view;
}  
#pragma -mark 向服务器请求购物车页面数据返回代理方法
- (void)getCarListEnd{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    if (self.carArray.count <= 0) {
        self.backView.hidden = NO;
        self.myCarTableView.hidden = YES;
        self.tabBarItem.badgeValue = nil;
    }else{
        self.backView.hidden = YES;
        self.myCarTableView.hidden = NO;
            self.myCarTableView.tableFooterView = [self crezteTableViewFoodView];
            self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%@",self.carlistModel.Amount];
    }
    NSLog(@"1=============   %@",self.carlistModel.DiscountPriceAmount);

    [self.myCarTableView reloadData];


}

#pragma -mark //请求服务器繁华的错误信息代理
- (void)getrequesterror:(NSString *)error{
     [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:error delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
#pragma -mark 网络异常代理／服务器起错误代理
- (void)requesterror{
     [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma －mark 向服务器改变商品数量代理方法
- (void)shopping_cat_TableViewCellEnd:(id)sender{

    
    CarModel *model = sender;
    self.carlistModel.DiscountPriceAmount = model.DiscountPriceAmount;
    self.carlistModel.MarketPriceAmount = model.MarketPriceAmount;
    _allPraceView.zeKou.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.DiscountPriceAmount.floatValue];
    _allPraceView.yu_e_Price.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.AmountCanUse.floatValue];
    _allPraceView.zonPrice.text= [NSString stringWithFormat:@"总金额:¥%.1f",self.carlistModel.MarketPriceAmount.floatValue];

    NSLog(@"1111===%@", self.carlistModel.MarketPriceAmount);
    
    [self.myCarTableView reloadData];
}

#pragma -mark 删除购物车结束代理方法
- (void)deleteCarProductEnd:(id)sender{

    CarModel *model = sender;
    self.carlistModel.DiscountPriceAmount = model.DiscountPriceAmount;
    self.carlistModel.MarketPriceAmount = model.MarketPriceAmount;
    
    NSLog(@"1111===%@", self.carlistModel.MarketPriceAmount);
    for (CarModel *myModel in self.carArray) {
        if ([model isEqual:myModel]) {
            [self.carArray removeObject:model];
            _allPraceView.zeKou.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.DiscountPriceAmount.floatValue];
            _allPraceView.yu_e_Price.text = [NSString stringWithFormat:@"¥%.1f",self.carlistModel.AmountCanUse.floatValue];
            _allPraceView.zonPrice.text= [NSString stringWithFormat:@"总金额:¥%.1f",self.carlistModel.MarketPriceAmount.floatValue];
             [self.myCarTableView reloadData];
            break;
        }
    }
   
    if (self.carArray.count <= 0) {
        self.backView.hidden = NO;
        self.myCarTableView.hidden = YES;
    }else{
        self.backView.hidden = YES;
        self.myCarTableView.hidden = NO;
    }
    
//    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
//    NSDictionary *dic = @{agentId:@"AgentID"};
//    [self.carArray removeAllObjects];
//    [self.carlistModel getCarList:self.carArray parameter:dic];
}

#pragma -mark 点击信封按钮事件
- (void)informationClick:(UIButton *)sender{

    InfoViewController *infomation =[[InfoViewController alloc] init];
    [self.navigationController pushViewController:infomation animated:YES];
}

#pragma -mark 打勾按钮事件
-(void)selectBut:(UIButton *)sener{
    self.boolbalance = @"";
    sener.selected = !sener.selected;
    if (sener.selected) {
        //使用余额
        self.boolbalance = @"1";
        
    } else{
        //不使用余额
        self.boolbalance = @"0";
        
    }
}

#pragma -mark 提交订单时的弹出输入密码提示框
-(void)careteAlertPassword{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
    
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [windows addSubview:_alertBackview];
    
    _zhiFuAlartView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndexedSubscript:12];
    _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
    _zhiFuAlartView.password.delegate = self;
    [_zhiFuAlartView.affirmBut addTarget:self action:@selector(affirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_zhiFuAlartView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [windows addSubview:_zhiFuAlartView];
    if ([self.boolbalance isEqualToString:@"0"]) {
        //不使用余额
        NSString *title = [NSString stringWithFormat:@"该行为将会从您绑定的银行卡中扣除¥%.f元",self.carlistModel.DiscountPriceAmount.floatValue];
        _zhiFuAlartView.titleAlart.text = title;
    } else{

        if (self.carlistModel.DiscountPriceAmount.floatValue >self.carlistModel.AmountCanUse.floatValue) {
            
            NSString *title = [NSString stringWithFormat:@"该行为将会从您的余额中扣除¥%.f元,从您绑定的银行卡中扣除¥%.f元",self.carlistModel.AmountCanUse.floatValue,self.carlistModel.DiscountPriceAmount.floatValue-self.carlistModel.AmountCanUse.floatValue];
            _zhiFuAlartView.titleAlart.text = title;
        }
        else{
            NSString *title = [NSString stringWithFormat:@"该行为将会从您的余额中扣除¥%.f元,从您绑定的银行卡中扣除¥0元",self.carlistModel.DiscountPriceAmount.floatValue];
            _zhiFuAlartView.titleAlart.text = title;
            
        }
    }
    
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_alertBackview addGestureRecognizer:_singleTap];
    _singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_zhiFuAlartView addGestureRecognizer:_singleTap2];
}
#pragma -mark 点击弹出框的确定交易
- (void)affirmClick{
    if (_zhiFuAlartView.password.text== nil ||[_zhiFuAlartView.password.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入支付密码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if (_zhiFuAlartView.password.text.length != 6) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入6位密码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
    
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [self shengChengKuCunList];
}
#pragma -mark 点击弹出框的取消交易
- (void)cancelButClick{
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
}
#pragma -mark 买库存
- (void)buyButClick:(UIButton *)sender{

//    sender.userInteractionEnabled = NO;

    [self careteAlertPassword];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, 100, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    return YES;
}

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSMutableString *text = [textField.text mutableCopy];
    [text replaceCharactersInRange:range withString:string];
    return [text length] <= 6;
}


#pragma -mark 改变tableView的fram值
- (void)showTableVierFram:(id)sender{
   [self.myCarTableView setContentOffset:CGPointMake(0, 100) animated:YES];
//    CarModel *model = sender;
//    for (int i = 0; i <self.carArray.count; i++) {
//        NSLog(@"bbbbbbbbbbbbbbbbb");
//        if ([model isEqual:self.carArray[i]]) {
//            NSIndexPath* indexPath = [NSIndexPath indexPathForItem:i inSection:0];
//            [self.myCarTableView scrollToRowAtIndexPath:indexPath
//                                       atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//            NSLog(@"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//            break;
//        }
//    }
}
- (void)showTableVierFramEnd:(id)sender{
   [self.myCarTableView setContentOffset:CGPointMake(0, 0) animated:YES];
 
}
#pragma -mark 买给客户
- (void)butUserButClick:(UIButton *)sender{
    
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (self.carArray.count <= 0) {
        return;
    }
    AddressViewController *myShoppingCV = [[AddressViewController alloc] init];
    [myShoppingCV.carModelArray addObjectsFromArray:self.carArray];
    myShoppingCV.carModel = self.carlistModel;
    myShoppingCV.isUseBalance = self.boolbalance;
    [self.navigationController pushViewController:myShoppingCV animated:YES];
}        

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.carArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;

}

#pragma -mark tableviewCell代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *shoppingCat1INdentfier1 = @"shoppingCat1";
    Shopping_cat_TableViewCell *shoppingCatcell1 =  [tableView dequeueReusableCellWithIdentifier:shoppingCat1INdentfier1];
    if (shoppingCatcell1 == nil) {
        shoppingCatcell1 = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] firstObject];
        
    }
    NSLog(@"数组的长度 ＝＝＝ %@",self.carArray);
    if (self.carArray.count <= 0) {
        UITableViewCell *tempCell = [[UITableViewCell alloc]init];
        return tempCell;
    }
    shoppingCatcell1.shopping_cat_TableViewCellDelegate = self;
    if (indexPath.row == self.carArray.count-1) {
        shoppingCatcell1.linelabel.hidden = YES;//隐藏最后一条线
    }
    
    [shoppingCatcell1 showMyCar:self.carArray[indexPath.row]];
    return shoppingCatcell1;
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        ApplyForViewController *apply = [[ApplyForViewController alloc] init];
        [self.navigationController pushViewController:apply animated:YES];
    }
}
#pragma -mark 点击支付按钮代理方法
- (void)getShoppingInfo:(id)sender{
    NSLog(@"点击了支付");
    AddressViewController *myShoppingCV = [[AddressViewController alloc] init];
    [self.navigationController pushViewController:myShoppingCV animated:YES];
}

#pragma -mark 向服务器请求生成买库存订单
- (void)shengChengKuCunList{
   
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    
    NSMutableArray *ProductInfoArr = [NSMutableArray array];
    
    for (CarModel *model in self.carArray) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:model.ProductID forKey:@"ProductID"];
        [dic setObject:model.Number forKey:@"Number"];
        [ProductInfoArr addObject:dic];
    }
    


    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];

    //提交库存订单的参数
    NSDictionary *parameter = @{@"AgentID":agentId,@"OrderTypeID":@"1",@"IsUseBalance":self.boolbalance,@"ProductInfo":ProductInfoArr,@"TradePass":_zhiFuAlartView.password.text};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    NSString *str = [self encodeString:jsonString key:PasswordKey];
    NSDictionary *paramer = @{@"sign":str};
    
    __weak Shopping_Cart_ViewController *carVC = self;
    [manager POST:ShengChengDinDanInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [GMDCircleLoader hideFromView:self.view animated:YES];
        
        NSString *str = responseObject[@"sign"];
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
    
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
            NSLog(@"提交库存订单返回结果 ＝＝＝＝ %@",dataDic);
            NSDictionary *dic = [dataDic objectForKey:@"data"];
            
            FinishStockViewController *finishStockVC = [[FinishStockViewController alloc] init];
            finishStockVC.masterOrderId = [NSString stringWithFormat:@"%@",dic[@"MasterOrderID"]];
            finishStockVC.carModel = carVC.carlistModel;
            finishStockVC.xiaDanTime = dic[@"AddTime"];
            [finishStockVC.carModelArray addObjectsFromArray:carVC.carArray];
            [carVC.navigationController pushViewController:finishStockVC animated:YES];

        }  else if ( [[dataDic objectForKey:@"status"] isEqualToString:@"failed"]) {
            NSRange range;
            range = [[dataDic objectForKey:@"reason"] rangeOfString:@"订单已生成"];
            if (range.location != NSNotFound) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"CarNumberChange"object:nil];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                [carVC.carArray removeAllObjects];
                if (carVC.carArray.count <= 0) {
                    carVC.backView.hidden = NO;
                    carVC.myCarTableView.hidden = YES;
                }else{
                    carVC.backView.hidden = YES;
                    carVC.myCarTableView.hidden = NO;
                }
                [carVC.myCarTableView reloadData];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
        } else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
   [GMDCircleLoader hideFromView:self.view animated:YES];
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];

}

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}
@end
